package cn.com.bod.fas.clm.common;

import com.google.code.appengine.awt.Color;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import fr.opensagres.xdocreport.itext.extension.font.ITextFontRegistry;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;


import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class WordToPDF {
	private static BaseFont bfChinese;

	static {
		try {
			// 配置字体文件路径 Fonts/simfang.ttf
			bfChinese = BaseFont.createFont("d:/tmp/simfang.ttf",
					BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		} catch (DocumentException | IOException e) {
			e.printStackTrace();
			try {
				bfChinese = BaseFont.createFont();
			} catch (DocumentException | IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * 将word文档， 转换成pdf, 中间替换掉变量
	 * 
	 * @param source 源为word文档， 必须为docx文档
	 * @param target 目标输出
	 * @param params 需要替换的变量
	 * @throws Exception
	 */
	public static void wordConverterToPdf(InputStream source, OutputStream target, Map<String, String> params)
			throws Exception {
		PdfOptions options = PdfOptions.create();
		IFontProvider fontProvider = new ITextFontRegistry() {
			@Override
			public Font getFont(String familyName, String encoding, float size, int style, Color color) {
				try {
					//Font fontChinese = new Font(bfChinese, size, style, color);
					Font fontChinese = new Font(bfChinese, size, style, color);
					if (familyName != null)
						{fontChinese.setFamily(familyName);}
					return fontChinese;

				} catch (Throwable e) {
					e.printStackTrace();
					return ITextFontRegistry.getRegistry().getFont(familyName, encoding, size, style, color);
				}
			}
		};
		options.fontProvider(fontProvider);
		wordConverterToPdf(source, target, options, params);
	}

	/**
	 * 将word文档， 转换成pdf, 中间替换掉变量
	 * 
	 * @param source  源为word文档， 必须为docx文档
	 * @param target  目标输出
	 * @param params  需要替换的变量
	 * @param options PdfOptions.create().fontEncoding( "windows-1250" ) 或者其他
	 * @throws Exception
	 */
	public static void wordConverterToPdf(InputStream source, OutputStream target, PdfOptions options,
			Map<String, String> params) throws Exception {
		XWPFDocument doc = new XWPFDocument(source);
		replaceText(doc.getParagraphs(), params);
		for (XWPFTable table : doc.getTables()) {
			for (XWPFTableRow row : table.getRows()) {
				for (XWPFTableCell cell : row.getTableCells()) {
					replaceText(cell.getParagraphs(), params);
				}
			}
		}
		PdfConverter.getInstance().convert(doc, target, options);
	}

	/** 替换段落中内容 */
	private static void replaceText(List<XWPFParagraph> paragraphs, Map<String, String> params) {
		if (null != params) {
			for (XWPFParagraph p : paragraphs) {
				for (XWPFRun r : p.getRuns()) {
					String content = r.getText(r.getTextPosition());
					if (StringUtils.isNotEmpty(content)) {
						for (Entry<String, String> entry : params.entrySet()) {
							content = content.replaceAll("\\$\\{" + entry.getKey() + "\\}",
									null == entry.getValue() ? "" : entry.getValue());
						}
						r.setText(content, 0);
					}
				}
			}
		}
	}

	public static void main(String[] args) {
		String filepath11 = "d:\\tmp\\11.docx";
		String outpath11 = "d:\\tmp\\11.pdf";

		InputStream source;
		OutputStream target;
		try {
			Map<String, String> params = new HashMap<String, String>();
			params.put("perLimitLoanNo", "12345");
			params.put("signDate", "20190728");
			params.put("custName", "金控");
			params.put("idCard", "610321");
			source = new FileInputStream(filepath11);
			target = new FileOutputStream(outpath11);

			wordConverterToPdf(source, target, params);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
